package tul.cot.lib.mapper;

import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;

import tul.cot.MigStats;
import tul.cot.MigrationTree;
import tul.cot.exception.ParseTreeException;
import tul.cot.job.Migrations.TaskMapper;
import tul.cot.util.TreeStats2;


public class MigMapper extends TaskMapper {
	
//	protected Logger LOG = Logger.getLogger(getClass());
	
	@Override
	protected void map(LongWritable key, Text treeStr, Context context)
		throws IOException, InterruptedException {
		
		LOG.debug(">map");
		
		MigrationTree tree = null;
		
		try {
			tree = new MigrationTree(treeStr.toString());
			tree.setTimes();
			
			LOG.debug("Tree:\n" + tree.toString());
		} catch (ParseTreeException e) {
			BAD_TREES_CNT.increment(1);
			
			LOG.error(e.getMessage());
			LOG.debug("Tree:\n" + treeStr.toString());
			LOG.debug("Parsed:\n" + e.getTreeStr());
			
			return;
		}
		
		if (!tree.isUltrametric(ULTRAMETRIC_EPS)) {
			NOT_ULTRAMETRIC_CNT.increment(1);
		}
		
		tree.makeUltrametric();
		
		// emit stats for all input pairs (incl dummy values)
		TreeStats2 treeStats = new TreeStats2(tree, START_TIME, NUM_SEG);
		
		for (int segNum = FIRST_SEG; segNum <= NUM_SEG; ++segNum) {
			MigStats stats = treeStats.getMigStats(segNum);
			emit_Stats(context, stats);
		}
		
		// emit all-tree-stats for Histograms
		MigStats stats = treeStats.getMigStats(-1);
		emit_DAI(context, stats);
		
		
		LOG.debug("<map");
	}
}
